<!-- 选择设备 -->

<template>
  <div>
    <BtnText v-if="one.deviceId" @click="toOpen">{{ one.deviceName }}</BtnText>

    <span v-if="!isShow">
      <BtnText v-if="one.deviceId" title="清除" class="marginRight" @click="toClear" />
      <BtnPrimary v-else title="选择" @click="toOpen" />
    </span>

    <EasyModal v-model="easyVisible" title="选择巡更设备" medium @submit="toSubmit" @close="toReset">
      <ChooseIOTOne :obj="obj" bind="device" />
    </EasyModal>
  </div>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'

const EMPTY = { id: '', deviceName: '' }

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'MyDevice',

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [CORE.mixWeb()],

  /**
   * 状态数据 (函数返回对象)
   */
  data() {
    return {
      easyVisible: false, // 弹窗是否可见
      obj: { device: CORE.clone(EMPTY) }, // 数据对象
    }
  },

  /**
   * 监听属性 (深度 deep 首次 immediate)
   */
  watch: {
    /**
     * 监听弹窗可见
     */
    visible(visible) {
      visible && this.toReset()
    },
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 弹窗
     */
    toOpen() {
      this.easyVisible = true
    },

    /**
     * 提交
     */
    toSubmit() {
      const { obj, one } = this
      one.deviceId = obj.device.id
      one.deviceName = obj.device.deviceName
      this.easyVisible = false
    },

    /**
     * 重置
     */
    toReset() {
      const { deviceId: id, deviceName } = this.one
      this.obj = { device: { id, deviceName } }
    },

    /**
     * 清除
     */
    toClear() {
      this.one.deviceId = ''
      this.one.deviceName = ''
      this.obj = { device: CORE.clone(EMPTY) }
    },
  },
}
</script>
